package com.bhkj.pdjhbgnewproject.core.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bhkj.pdjhbgnewproject.R;
import com.bhkj.pdjhbgnewproject.common.bean.PdInfoBean;
import com.bhkj.pdjhbgnewproject.common.bean.PersonInfoBean;
import com.bhkj.pdjhbgnewproject.common.callback.CallbackManager;
import com.bhkj.pdjhbgnewproject.common.callback.IGlabolCallback;
import com.bhkj.pdjhbgnewproject.common.contanct.Contacts;
import com.bhkj.pdjhbgnewproject.common.utils.FileUtil;
import com.bhkj.pdjhbgnewproject.common.work.WorkHelper;
import com.bhkj.pdjhbgnewproject.core.service.ObtainPdInfoService;
import com.bhkj.pdjhbgnewproject.core.service.WsDataManager;
import com.bhkj.pdjhbgnewproject.core.viewmodel.MainViewRealModel;
import com.bhkj.pdjhbgnewproject.core.viewmodel.WindowStatusModel;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.SnackbarUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class MainHandler {
    private List<String> datas = new ArrayList<>();
    private TextView dwTv, windowNameTv, dateTv, currentNumTv, currentNumTipTv, waitNumTv;
    private TimerTask timerTask;
    private Timer timer;
    private ImageView iconIv;
    private ConstraintLayout rootView;
    private RecyclerView waitNumRv;

    private IMainView iMainView;
    private MainAdapter adapter;

    public MainHandler(IMainView iMainView) {
        NetworkUtils.registerNetworkStatusChangedListener(new NetworkUtils.OnNetworkStatusChangedListener() {
            @Override
            public void onDisconnected() {

            }

            @Override
            public void onConnected(NetworkUtils.NetworkType networkType) {
                AppUtils.relaunchApp(true);
            }
        });
        ServiceUtils.startService(ObtainPdInfoService.class);
//        new PdinfoManager();
        WorkHelper.reLauncherWork();
        this.iMainView = iMainView;
        initView();
        showDate();
        new WsDataManager();
    }

    /**
     * 初始化视图控件
     */
    private void initView() {
        SPUtils.getInstance().remove(Contacts.WINDOW_STATUS);
        iconIv = iMainView.findViewById(R.id.iv_main_police_icon);
        dwTv = iMainView.findViewById(R.id.tv_main_dw);
        windowNameTv = iMainView.findViewById(R.id.tv_main_window_name);
        dateTv = iMainView.findViewById(R.id.tv_main_date);
        currentNumTv = iMainView.findViewById(R.id.tv_main_current_num);
        waitNumRv = iMainView.findViewById(R.id.rv_main_real);
        currentNumTipTv = iMainView.findViewById(R.id.tv_main_blnm);
        waitNumTv = iMainView.findViewById(R.id.tv_main_waitnum);
        rootView = iMainView.findViewById(R.id.rootView);
        if (iMainView.getResources().getBoolean(R.bool.isYsd)) {
            waitNumRv.setVisibility(View.GONE);
        }
        initRecyclerView();
        obtainDeptInfo();
    }

    private void initRecyclerView() {
        GridLayoutManager manager = new GridLayoutManager(iconIv.getContext(), 2);
        waitNumRv.setLayoutManager(manager);
        adapter = new MainAdapter(R.layout.item_wait_num, null);
        adapter.bindToRecyclerView(waitNumRv);
    }


    private void obtainDeptInfo() {
        final MainViewModel mainViewModel = new MainViewModel(iMainView.getResources(), iconIv, rootView, dwTv, windowNameTv);
        mainViewModel.obtainWindowShowInfo();
        NetworkUtils.registerNetworkStatusChangedListener(new NetworkUtils.OnNetworkStatusChangedListener() {
            @Override
            public void onDisconnected() {
                SnackbarUtils.with(windowNameTv)
                        .setMessage("网络不可用")
                        .showWarning();
            }

            @Override
            public void onConnected(NetworkUtils.NetworkType networkType) {
                SnackbarUtils.dismiss();
                //网络有变化的时候初始化
                mainViewModel.obtainWindowShowInfo();
            }
        });
    }


    /**
     * 更新窗口信息
     *
     * @param personInfoBean
     */
    private void setWindowInfo(PersonInfoBean personInfoBean) {

        if (ObjectUtils.isNotEmpty(personInfoBean) && ObjectUtils.isNotEmpty(personInfoBean.getDatas())) {
            String dept = personInfoBean.getDatas().getDEPTID();
            PersonInfoBean.DatasBean datas = personInfoBean.getDatas();

            if (dept != null) {
                rootView.setBackgroundResource(R.drawable.bg);
                if (dwTv != null) {
                    dwTv.setText(datas.getDEPTNAME());
                }
                String windowNum = datas.getNAME();
                if (windowNameTv != null && ObjectUtils.isNotEmpty(windowNum)) {
                    windowNameTv.setText(windowNum);
                }
//                                SPUtils.getInstance().put(Contacts.PARAM_WINDOW, datas.getName());
//                                SPUtils.getInstance().put(Contacts.PARAM_DEPT, datas.getDeptname());
                Glide.with(iconIv.getContext()).load(datas.getLOGO()).into(iconIv);
                String windowStatus = SPUtils.getInstance().getString(Contacts.WINDOW_STATUS);
                if (ObjectUtils.equals(windowStatus, Contacts.PUSH_LOGIN) ||
                        ObjectUtils.equals(windowStatus, Contacts.PUSH_RESUME_SERVICE)) {
                    rootView.setBackgroundResource(R.drawable.bg);
                } else {
//                    setRootBackground(this.datas.getUrl());


                }

            }
        } else {
            ToastUtils.showShort("获取窗口信息为空");
        }
    }


    /**
     * 刷新界面排队信息
     *
     * @param pdInfo 服务端返回的排队信息
     */
    private void updatePdInfo(String pdInfo) {
//        String path1= Environment.getExternalStorageDirectory().getPath()+"/updateLog/log.txt";
//        LogUtils.d("路径："+path1);
        try {
            PdInfoBean pdInfoBean = GsonUtils.fromJson(pdInfo, PdInfoBean.class);

            PdInfoBean.DatasBean dataRes = pdInfoBean.getDatas();
            if (ObjectUtils.isEmpty(dataRes)) {
                currentNumTv.setText(StringUtils.getString(R.string.empty));
                setEmpty();
                return;
            }

            if (ObjectUtils.isNotEmpty(dataRes.getQueuenumber())) {
                currentNumTv.setText(dataRes.getQueuenumber());
            } else {
                currentNumTv.setText(StringUtils.getString(R.string.empty));
            }

            List<PdInfoBean.DatasBean.DatasBeans> pdList = dataRes.getDatas();
            if (ObjectUtils.isNotEmpty(pdList)) {
                if (ObjectUtils.isNotEmpty(datas)) {
                    datas.clear();
                }
                int size = pdList.size();
                for (int i = 0; i < size; i++) {
                    PdInfoBean.DatasBean.DatasBeans nextQueueBean = pdList.get(i);
                    if (i == 5) {
                        datas.add("······");
                    } else if (size == 1) {
                        datas.add(nextQueueBean.getQUNUMBER());
                    } else {
                        datas.add(getXh(i, nextQueueBean));
                    }
                }

//                for (PdInfoBean.DatasBean.NextQueueBean queueNum : pdList) {
//                    this.datas.add(queueNum.getQunumber());
//                }

                if (ObjectUtils.isEmpty(datas)) {
                    setEmpty();
                } else {
                    adapter.setNewData(datas);
                }
            } else {
                setEmpty();
            }

        } catch (Exception e) {
            String path = Environment.getExternalStorageDirectory().getPath() + "/updateLog/log.txt";
            FileUtil.writeFile(path, AppUtils.getAppPackageName() + "-updatePdInfo:" + e.getMessage() + "\n" + pdInfo + "\n");
        }


    }


    private String getXh(int index, PdInfoBean.DatasBean.DatasBeans nextQueueBean) {
        return (index + 1) + "." + nextQueueBean.getQUNUMBER();
    }

    private void setEmpty() {
        adapter.setNewData(null);
        adapter.setEmptyView(R.layout.item_wait_num);
        TextView emptyTip = adapter.getEmptyView().findViewById(R.id.tv_wait_num);
        emptyTip.setText(StringUtils.getString(R.string.empty));
    }


    /**
     * 叫号器端登陆开启获取排队信息
     * 叫号器端注销关闭获取排队信息
     * 更新排队信息
     */
    public void startAndRefreshPdInfo() {

        CallbackManager.getInstance().addCallback(Contacts.FRESH_PD_INFO, new IGlabolCallback<String>() {
            @Override
            public void executeCallback(String freshPdInfo) {
                updatePdInfo(freshPdInfo);
            }
        });


        MainActivity topActivity = (MainActivity) ActivityUtils.getTopActivity();
        if (topActivity != null) {
            MainViewRealModel mainViewRealModel = ViewModelProviders.of(topActivity).get(MainViewRealModel.class);
            LogUtils.d("执行了");
            mainViewRealModel.getPersonInfoLiveData().observe(topActivity, new Observer<PersonInfoBean>() {
                @Override
                public void onChanged(@Nullable PersonInfoBean personInfoBean) {
                    showOrHideView(true);
                    setWindowInfo(personInfoBean);
                }
            });

            WindowStatusModel windowStatusModel = ViewModelProviders.of(topActivity).get(WindowStatusModel.class);
            windowStatusModel.getWindowStatusLiveData().observe(topActivity, new Observer<String>() {
                @Override
                public void onChanged(@Nullable String s) {
                    switch (Objects.requireNonNull(s)) {
                        case Contacts.PUSH_END_SERVICE:
                        case Contacts.PUSH_LOGOUT:
                            rootView.setBackgroundResource(R.drawable.ic_w);
                            showOrHideView(false);
                            break;
                        case Contacts.PUSH_RESUME_SERVICE:
                            rootView.setBackgroundResource(R.drawable.bg);
                            showOrHideView(true);
                            break;
                        default:
                            break;
                    }
                }
            });
        }
    }


    private void showOrHideView(boolean isShow) {
        int visible = isShow ? View.VISIBLE : View.GONE;
        dateTv.setVisibility(visible);
        currentNumTv.setVisibility(visible);
        waitNumRv.setVisibility(visible);
        waitNumTv.setVisibility(visible);
        currentNumTipTv.setVisibility(visible);
    }


    /**
     * 关闭界面清除定时器
     * 关闭访问排队信息服务
     */
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }


    /**
     * 显示当前的日期,每隔一秒刷新一次
     */
    private void showDate() {
        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    Activity topActivity = ActivityUtils.getTopActivity();
                    if (topActivity != null) {
                        topActivity.runOnUiThread(new Runnable() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void run() {
                                Date date = new Date();
                                dateTv.setText("\n" + TimeUtils.date2String(date, "MM月dd日") + "  " + getWeek(date));
                            }
                        });
                    }
                }
            };

        }

        timer.schedule(timerTask, 0, 1000);
    }

    /**
     * 显示星期x格式
     *
     * @param date Date
     * @return 星期x
     */
    private String getWeek(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 EEEE");
        format = new SimpleDateFormat("EEEE");
        return format.format(date);
    }
}